package com.netty.client;

import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.qbb.client.bean.active.SocketBean;
import com.qbb.client.bean.result.SocketResultBean;
import com.qbb.client.bean.services.QbbAttrBean;
import com.qbb.client.constant.QbbConfigUtil;
import com.qbb.client.exception.NettyException;

/**
 * 类说明
 * 
 * @author chenhuaiao
 * @version V1.0 创建时间：Mar 11, 2015 11:35:53 AM
 */
public class QbbClient {
	private static Log log = LogFactory.getLog(QbbClient.class);
	// UUID操作相关的对象控制
	public static Map<String, String> activeMaps = new ConcurrentHashMap<String, String>();
	public static Map<String, SocketResultBean> readMaps = new ConcurrentHashMap<String, SocketResultBean>();
	public static Queue<String> activeQueue = new LinkedList<String>();

	private QbbClient() {
	}

	/**
	 * 调用指定的服务
	 * 
	 * @param serverName
	 * @return
	 */
	public static Map<String, Object> call(String serverName) {
		QbbAttrBean config = QbbConfigUtil.getProper(serverName);
		if (config == null) {
			throw new NettyException("客户端定义的关联服务接口的配置中,找不到定义的serverName['"
					+ serverName + "']");
		}
		SocketBean socketBean = SocketBean.getBean(serverName);
		return inCall(config.getIp(), config.getPort(), socketBean);
	}

	/**
	 * 提供外部调用,通信结果返回
	 * 
	 * @param serverName
	 * @param paramObj
	 * @return
	 */
	public static Map<String, Object> call(String serverName,
			Map<String, Object> paramObj) {
		if (paramObj == null) {
			throw new NettyException("调用的服务接口serverName[" + serverName
					+ "],传递的参数信息不能为空!");
		}
		QbbAttrBean config = QbbConfigUtil.getProper(serverName);
		if (config == null) {
			throw new NettyException("客户端定义的关联服务接口的配置中,找不到定义的serverName['"
					+ serverName + "']");
		}
		SocketBean socketBean = SocketBean.getBean(serverName, paramObj);
		return inCall(config.getIp(), config.getPort(), socketBean);
	}

	/**
	 * 内部解析结果集之后的调用
	 * 
	 * @param host
	 * @param port
	 * @param socketBean
	 * @return
	 */
	private static Map<String, Object> inCall(String host, int port,
			SocketBean socketBean) {
		QbbThreadCall instance = new QbbThreadCall();
		instance.setPort(port);
		instance.setHost(host);
		instance.setSocketBean(socketBean);

		log.info("Qbbclient call ip[" + host + "],port[" + port + "]");

		return instance.runStart();
	}
}